
#include <QtCore/QCoreApplication>
 
#include "../src/corelib/tools/qstring.h"
#include "../src/corelib/io/qfile.h"
#include "../src/corelib/io/qtextstream.h"
#include "csvline.h"
#include "outinfo.h"
#include <iostream>
using namespace std;
struct Config {
	QString inputFile;
	int thresSec;
	bool skipHead;
	Config() {
		thresSec=5;
		skipHead=false;
	}
}CFG;

void usage(int argc,char*argv[]) {
	perror("usage : miniTLN [-h] [-s second] <timegen_output_csv> \n"
		"\t -h : skip header\n"
		"\t -s second : combine events occurred in a interval of <second> seconds\n");
	exit(1);
}

int setConfig(int argc, char *argv[]) {
	for(int i = 1;i<argc;i++)
	{
		if (strcmp(argv[i],"-h")==0)
			CFG.skipHead=true;
		else if (strcmp(argv[i],"-s")==0)
			CFG.thresSec = atoi(argv[++i]);
		else if (strncmp(argv[i],"-",1)==0) {
			cerr<<"bad parameter "<<argv[i]<<endl;
			exit(1);
		} else CFG.inputFile = argv[i];
	}
	if (CFG.inputFile.isEmpty())
		usage(argc,argv);
	return true;
}

enum COLUMN {
	
};


QList<OutInfo> listout;

void insertNewLine( LineInfo &line ) 
{
	int i;
	OutInfo outinfo(line);
	for(i=0;i<listout.size();i++)
		if (listout[i].getPrefix()==outinfo.getPrefix()) {
			listout[i].combine(outinfo);
			return;
		}
	listout.push_back(outinfo);

}

int main(int argc, char *argv[])
{
	QCoreApplication a(argc, argv);
	setConfig(argc,argv);
	QFile ifile(CFG.inputFile);
	if (!ifile.open(QIODevice::ReadOnly)) {
		fprintf(stderr,"can not open file to read: %s\n",CFG.inputFile.toStdString().c_str());
	}
	QTextStream is(&ifile);
	QTextStream qout(stdout);
	QTextStream qerr(stderr);
	QString _;
	if (CFG.skipHead)
		is.readLine();
	qout<<"time,src,host,usr,action,target,misc,tamper\n";
	QDateTime lastDT;
	int incnt=0,outcnt=0;
	while (true) {
		_=is.readLine();
		if (_.isEmpty()) break;
		CSVLine csvline(_);
		LineInfo info(csvline);
		QDateTime thres = info.time.addSecs(CFG.thresSec);
#ifdef _DEBUG
		qerr<<"lastdt:"<<lastDT.toString()<<"info.time:"<<info.time.toString()<<endl;
#endif // _DEBUG
		if (lastDT.isValid() && info.time>lastDT) {
			cerr<<"time column is not in decreasing order EXITING...";
			exit(1);
		}
		lastDT = info.time;
		//output 
		QMutableListIterator<OutInfo> it(listout);
		while (it.hasNext()) {
			OutInfo & outinfo = it.next();
			if (outinfo.beginTime>thres) {
				qout<<outinfo.toString()<<endl;
				it.remove();
				outcnt++;
			}
		}
		insertNewLine(info);
		incnt++;
		cerr<<"in cnt: "<<incnt<<"out cnt:"<<outcnt<<"\r";
	}
	for(int i = 0;i<listout.size();i++)
		qout<<listout[i].toString()<<endl;
	return 0;
}
